<template>
	<div class="system-role">
		<Modal v-model="showPermissionModal" width="360">
			<p slot="header" style="color:#f60">
				<span>权限详情</span>
			</p>
			<div>
				<p v-for="(item,i) in permissionIds" :key="i">{{item.permissionName}}</p>
			</div>
		</Modal>
		<div class="top">
			<Row :gutter="10" justify="center">
				<Col span="4">
					<Button type="success" icon="md-add" @click="showDrawer=true;">新增</Button>
				</Col>
			</Row>
		</div>
		<Drawer :title="alertTitle" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form ref="form" :model="editedItem" :rules="rules" :label-width="80">
				<Row :gutter="32">
					<Col :span="24">
                        <FormItem label="随访类型" label-position="left" prop="templateType">
							<Select v-model="editedItem.templateType" class="cube" placeholder="选择随访类型">
                                <Option
                                    v-for="item in typeFollowList"
                                    :value="item.itemKey"
                                    :key="item.id"
                                >{{ item.itemValue }}</Option>
                            </Select>
						</FormItem>
					</Col>
                    <Col :span="24">
						<FormItem label="模板名称" label-position="left" prop="templateName">
							<Input v-model="editedItem.templateName" placeholder="" />
						</FormItem>
					</Col>
                    <Col :span="24">
						<FormItem label="模板内容" label-position="left" prop="templateContent">
							<Input type="textarea" show-word-limit :maxlength="200" v-model="editedItem.templateContent" placeholder="" />
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" :loading="editedIndex===-1?createLoading:updateLoading" @click="save">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
				>
					<template slot-scope="{ row }" slot="sex">
                        <span v-if="Number(row.sex)===1">男</span>
                        <span v-else-if="Number(row.sex)===2">女</span>
                        <span v-else>-</span>
					</template>
					<template slot-scope="{row}" slot="createTime">
						<span>{{row.createTime | YMDHMS}}</span>
					</template>

                    <template slot-scope="{row}" slot="templateType">
						<!-- <span>{{row.templateType}}</span> -->
						<span>{{getTemplateName(row.templateType)}}</span>
                        
					</template>
                    
					<template slot-scope="{row}" slot="updateTime">
						<span>{{row.updateTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="action">
						<Button v-if="row.rolename !== 'ADMIN'" type="primary" size="small" @click="update(row)">修改</Button>
						<Button
							v-if="row.rolename !== 'ADMIN'"
							class="ml10"
							type="primary"
							ghost
							size="small"
							@click="remove(row)"
						>删除</Button>
					</template>
				</Table>
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { templateFollowPageQueryList, templateFollowAdd, templateFollowUpdate, templateFollowDelete } from '@api/followTemplate.js'
import { mapState } from '@lib/x_.js' 
export default {
	data() {
		return {
            rules:{
                templateType: [{required: true, message: '请选择随访类型', trigger: 'blur' }],
                templateName: [{required: true, message: '请输入模板名称', trigger: 'blur' }],
                templateContent: [{required: true, message: '请输入描述内容', trigger: 'blur' }],
            },
			showDrawer: false,
			showPermissionModal: false,
			loading: false,
			createLoading: false,
			updateLoading: false,
			removeLoading: false,
			editedIndex: -1,
			permissionIds: [],
			editedItem: {
				templateType: '',
				templateName: '',
				templateContent: '',
			},
			defaultItem: {
				templateType: '',
				templateName: '',
				templateContent: '',
			},
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			permissionList: [],
			tableColumns: [
				{
					title: '模板名称',
					width: 200,
					key: 'templateName'
                },
                {
					width: 200,
					title: '模板类型',
					slot: 'templateType'
				},
				{
					width: 200,
					title: '模板内容',
					key: 'templateContent'
                },
                {
					title: '最后操作人',
					width: 200,
					key: 'updateUsername'
                },
                {
					width: 200,
					title: '最后操作时间',
					slot: 'updateTime'
				},
				{
					title: '创建时间',
					width: 200,
					slot: 'createTime'
				},
				{
					title: '操作',
					slot: 'action',
					width: 200,
                },
                {
					title: ' ',
					key: '',
				},
			]
		}
	},
	mounted() {
        this.templateFollowPageQueryList()
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
        },
        ...mapState(['typeFollowList']),
	},
	methods: {
        getTemplateName(type){
            if (type) {
                const idx = this.typeFollowList.findIndex((item,i) => (item.itemKey) === String(type))
                if (idx  > -1) {
                    return this.typeFollowList[idx]['itemValue']
                }
                return ''
            }
            return ''
        },
		pageChange(page) {
			if (this.loading) {
				return
			}
			this.page = page
			this.templateFollowPageQueryList()
			console.log('page>', page)
		},
		async update(item) {
			const { id } = item
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
			this.showDrawer = true
		},
		create() {
			this.editedIndex = -1
			this.editedItem = Object.assign({}, this.defaultItem)
			this.showDrawer = true
		},
        remove(item, idx) {
			//done this.close();
			const { templateName, id } = item
			this.removeLoading || (this.removeLoading = true)
			this.$Modal.confirm({
				title: '删除',
				content: `是否删除模板: ${templateName}?`,
				onOk: async () => {
					const res = await templateFollowDelete({ id })
					this.modal(res, '删除')
					this.templateFollowPageQueryList()
					this.$Modal.remove()
                    this.removeLoading = false
                    this.$store.dispatch('templateFollowPageQueryList')
				}
			})
		},
		async save() {
			console.log('this.$Modal-->', this.$Modal)
			if (this.editedIndex > -1) {
                console.log('update...')
                const {id, templateType, templateName, templateContent } = this.editedItem
                
                if (!templateType) {
                    return this.$Message.error('请选择模板类型')
                }
                if (!templateName) {
                    return this.$Message.error('请输入模板名称')
                }
                if (!templateContent) {
                    return this.$Message.error('请输入模板内容')
                }

				this.updateLoading || (this.updateLoading = true)
				const res = await templateFollowUpdate({ id, templateType, templateName, templateContent})
				this.updateLoading = false
				this.modal(res)
			} else {
                const { templateType, templateName, templateContent } = this.editedItem
                
                if (!templateType) {
                    return this.$Message.error('请选择模板类型')
                }
                if (!templateName) {
                    return this.$Message.error('请输入模板名称')
                }
                if (!templateContent) {
                    return this.$Message.error('请输入模板内容')
                }

				this.createLoading || (this.createLoading = true)
                const res = await templateFollowAdd({ templateType, templateName, templateContent })
                this.$store.dispatch('templateFollowPageQueryList')
				this.createLoading = false
                this.modal(res)
				//create
			}
            this.templateFollowPageQueryList()
			this.close()
		},
		modal(res, title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
				})
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg
				})
			}
		},
		close() {
            this.showDrawer = false
            this.$refs['form'].resetFields();
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
		templateFollowPageQueryList() {
			const { page, pageSize, loading } = this
			if (loading) return
			this.loading = true
			templateFollowPageQueryList({
				page,
				pageSize
			})
				.then(res => {
					this.loading = false
					console.log('res roles->', res)
					if (res.code === '0') {
						const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
						;(this.items = items), (this.page = currentPage), (this.totalNum = totalNum)
						console.log('this.items->', this.items)
					} else {
						this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
						})
					}
				})
				.catch(err => {
					this.loading = false
				})
		}
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped>
.system-role {
	background-color: #fff;
}
</style>